#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@IDE     ：PyCharm 
@Author  ：kiway
@Date    ：2024/11/10 10:29 
"""

import zmq
import zmq.asyncio
import asyncio
import multiprocessing
import time
import sys
if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


# 发布者函数
def publisher():
    context = zmq.asyncio.Context()
    socket = context.socket(zmq.PUB)
    socket.bind("tcp://*:5555")

    async def publish():
        while True:
            message = "Hello, world!"
            await socket.send_string(message)
            print(f"Published: {message}")
            await asyncio.sleep(1)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(publish())


# 订阅者函数
def subscriber():
    context = zmq.asyncio.Context()
    socket = context.socket(zmq.SUB)
    socket.connect("tcp://localhost:5555")
    socket.setsockopt_string(zmq.SUBSCRIBE, "")

    async def subscribe():
        while True:
            message = await socket.recv_string()
            print(f"Received: {message}")

    loop = asyncio.get_event_loop()
    loop.run_until_complete(subscribe())


# 多进程主函数
def main():
    # 创建发布者和订阅者进程
    publisher_process = multiprocessing.Process(target=publisher)
    subscriber_process = multiprocessing.Process(target=subscriber)

    # 启动进程
    publisher_process.start()
    subscriber_process.start()

    # 等待进程结束
    publisher_process.join()
    subscriber_process.join()


if __name__ == "__main__":
    main()
